package org.momo.rpc.ratelimit.impl;


import org.momo.rpc.ratelimit.RateLimiter;

import java.util.concurrent.atomic.AtomicInteger;

public class FixedRateLimiter implements RateLimiter {

    private final int interval;

    private final int permitPerInterval;

    private final AtomicInteger currentRequestCount = new AtomicInteger(0);

    private long lastIntervalBeginTimestamp = System.currentTimeMillis();

    public FixedRateLimiter(int interval, int permitPerInterval) {
        this.interval = interval;
        this.permitPerInterval = permitPerInterval;
    }

    @Override
    public synchronized boolean limit() {
        long currentTimestamp = System.currentTimeMillis();

        if(currentTimestamp - lastIntervalBeginTimestamp >= interval) {
            lastIntervalBeginTimestamp = System.currentTimeMillis();
            currentRequestCount.set(1);
            return true;
        } else {
            currentRequestCount.incrementAndGet();
            return currentRequestCount.get() <= permitPerInterval;
        }
    }

}
